import React, { PureComponent } from 'react';
import { message, Form, Input, Divider, Table, Icon, Button } from 'antd';
import { connect } from 'dva';
import SyOrderTableComponent from '../../components/SyOrderTableComponent';
import { SyOrderTableBasicFormComponent } from '../../components/SyOrderTableComponent';
import baseStyles from '../../components/SyOrderTableComponent/index.less';
import moment from 'moment';


@Form.create()
@connect(state => ({
  modelState: state.withdrawBill,
}))
export default class WithdrawHaveRepayed extends SyOrderTableComponent {

  // 缺省
  _initSortion = { sortField: 'id', sortOrder: 'desc', };
  _initPagination = { pageSize: 20, current: 1, };
  _initCriteriaQuery = { status: 'have-repayed' };
  _operator = [

  ];

  initSelection() {
    const { dispatch } = this.props;
    dispatch({
      type: 'withdrawBill/fetchHaveRepayedWithdrawCount',
      payload: {
        userName: '',
        mobile: '',
        withdrawId: '',
        startDate: '',
        endDate: ''
      }
    });
  }

  componentWillMount() {
    this.initSelection();
    this.setState({
      baseModel: 'withdrawBill',
      operator: this._operator,
      initPagination: this._initPagination,
      initSortion: this._initSortion,
      initCriteriaQuery: this._initCriteriaQuery,
      needSearch: true,
      needAdd: false,
      needEdit: false,
      needDelete: false,
      needTableColumnsOperator: false,
      needTableCheckbox: true,
      needTableStatistics: true,
      tableBorder: false,
      // defaultExpandAllRows: true,
      statusField: 'status',
      tableScroll: { y: 800 },
      tableColumns: [
        // {
        //   title: '用户ID',
        //   dataIndex: 'userId',
        //   width: 180,
        // },
        {
          title: '订单号',
          dataIndex: 'withdrawId',
          width: 180,
          fixed: 'left',
        },
        {
          title: '客户姓名',
          dataIndex: 'userName',
          width: 120,
          fixed: 'left',
        },
        {
          title: '性别',
          dataIndex: 'gender',
          width: 70,
          fixed: 'left',
        },
        {
          title: '手机号',
          dataIndex: 'mobile',
          width: 120,
          fixed: 'left',
        },
        {
          title: '申请时间',
          dataIndex: 'applyTime',
          width: 140,
          render: (text, record) => <span>{record.applyTime ? moment(record.applyTime).format('YYYY-MM-DD HH:mm') : '/'}</span>,
        },
        {
          title: '放款时间',
          dataIndex: 'startTime',
          width: 140,
          render: (text, record) => <span>{record.startTime ? moment(record.startTime).format('YYYY-MM-DD HH:mm') : '/'}</span>,
        },
        {
          title: '应还时间',
          dataIndex: 'endTime',
          width: 140,
          render: (text, record) => <span>{record.endTime ? moment(record.endTime).format('YYYY-MM-DD HH:mm') : '/'}</span>,
        },
        {
          title: '末次还款时间',
          dataIndex: 'repayTime',
          width: 140,
          render: (text, record) => <span>{record.repayTime ? moment(record.repayTime).format('YYYY-MM-DD HH:mm') : '/'}</span>,
        },
        {
          title: '周期',
          dataIndex: 'period',
          width: 80,
        },
        {
          title: '逾期天数',
          dataIndex: 'overdueLength',
          width: 90,
        },
        {
          title: '已还金额',
          dataIndex: 'repayAmount',
          width: 120,
          render: (text, record) => <span>￥ {record.repayAmount}</span>,
        },
        {
          title: '借款金额',
          dataIndex: 'withdrawAmount',
          width: 120,
          render: (text, record) => <span>￥ {record.withdrawAmount}</span>,
        },
        {
          title: '利息',
          dataIndex: 'interestAmount',
          width: 100,
          render: (text, record) => <span>￥ {record.interestAmount}</span>,
        },
        {
          title: '逾期利息',
          dataIndex: 'fineAmount',
          width: 90,
          render: (text, record) => <span>￥ {record.fineAmount}</span>,
        },
        // {
        //   title: '银行卡号',
        //   dataIndex: 'bankCardNum',
        //   width: 180,
        // },
        // {
        //   title: '所属银行',
        //   dataIndex: 'bankName',
        //   // width: 220,
        // },
        {
          title: '借款次数',
          dataIndex: 'withdrawTimes',
          // width: 100,
        },
        // {
        //   title: '信用报告',
        //   dataIndex: 'userReport',
        //   width: 100,
        //   fixed: 'right',
        //   render: (text, record) =>
        //     <a onClick={() => {
        //       this.setState({ editedEntity: record });
        //     }}>
        //       查 看
        //    </a>,
        // },
        // {
        //   title: '操作',
        //   dataIndex: 'operatoer',
        //   width: 80,
        //   fixed: 'right',
        //   render: (text, record) =>
        //     <a onClick={() => {
        //       this.setState({ editedEntity: record });
        //       this.handleOperator(true, '放 款', this.billForm, null, this.renderBillForm, record, () => this.onRepayClick(record), null, this.renderBillModalFootButton, null)
        //     }}>
        //       放 款
        //    </a>,
        // },
      ],
      searchFormItem: [
        {
          name: 'userName',
          label: '姓名',
          placeholder: '姓名',
          type: 'string',
        },
        {
          name: 'mobile',
          label: '手机号',
          placeholder: '手机号',
          type: 'string',
        },
        {
          name: 'startDate',
          label: '起始日期',
          placeholder: '起始日期',
          type: 'dateTime',
          showTime: false,
        },
        {
          name: 'endDate',
          label: '截止日期',
          placeholder: '截止日期',
          type: 'dateTime',
          showTime: false,
        },
        {
          name: 'withdrawId',
          label: '订单号',
          placeholder: '订单号',
          type: 'string',
        },
      ],
      repayModalVisible: false,
    });
  }

  onRepayClick = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'instalmentAlreadyPayOrder/queryRepayItemById',
      payload: { orderId: record.orderId },
    });
    dispatch({
      type: 'instalmentAlreadyPayOrder/queryBillItemById',
      payload: { orderId: record.orderId },
    });
  }

  renderBillModalFootButton = [
    <Button key="transferFail" type="danger" loading={this.props.modelState.operatorLoading} onClick={() => this.handleTransferEvent(false)}
      style={{ float: 'left' }}
    >
      手动打款失败
    </Button>,
    <Button disabled key="transferByYb" type="primary" loading={this.props.modelState.operatorLoading} onClick={() => { /**/ }}
      style={{ marginRight: 24 }}
    >
      易宝打款
    </Button>,
    <Button key="transferSuccess" type="primary" loading={this.props.modelState.operatorLoading} onClick={() => this.handleTransferEvent(true)}>
      手动打款
    </Button>,
  ];


  billFormItem = [
    {
      name: 'remark',
      label: '备注',
      placeholder: '备注',
      type: 'longString',
    },
  ];

  renderBillForm = () => {
    const { form, modelState: { selectItems } } = this.props;
    return (
      <SyOrderTableBasicFormComponent
        ref={this.saveBillFormFormRef}
        formItems={this.billFormItem}
        selectItems={selectItems}
      >

      </SyOrderTableBasicFormComponent>
    );
  }

  saveBillFormFormRef = (form) => {
    this.billForm = form;
  }


  handleTransferEvent = (success) => {
    const { dispatch } = this.props;
    const { editedEntity } = this.state;
    const form = this.billForm;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (!success && (!fieldsValue.remark || fieldsValue.remark.length == 0)) {
        form.setFields({
          remark: {
            value: fieldsValue.remark,
            errors: [new Error('手动打款失败必须填写备注'),]
          }
        });
        return;
      }

      let value = {
        withdrawId: editedEntity.withdrawId,
        isSuccess: success,
      };
      if (fieldsValue.remark && fieldsValue.remark.length > 0) {
        value.remark = fieldsValue.remark;
      }

      dispatch({
        type: this.state.baseModel + '/manualTransfer',
        payload: { ...value },
        callback: (code, msg) => {
          if (code == 200) {
            message.success(msg);
            this.resetCurrentForm();
            dispatch({
              type: this.state.baseModel + '/fetch',
              payload: {
                ...this.state.initPagination,
                ...this.state.initSortion,
                ...this.state.initCriteriaQuery,
                ...this.state.statusQuery,
                queryUrl: this.state.queryUrl,
              }
            });
          } else {
            message.error(msg);
          }
        },
      });
    });
  }


  /* ***************************************************************** */

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    super.componentDidMount();
  }

}
